package com.xiaoma.juc.semaphore;

import java.util.concurrent.Semaphore;

/**
 * @ClassName ProcessLimitor
 * @Description
 * @date 2020-09-28 15:58
 */
public class ProcessLimitor {

    private final Integer maxProcess = 1;
    private Integer currently = 0;
    private int a = 0;
    private Semaphore semaphore = new Semaphore(maxProcess);

    public void handle(int num) {
        try {
            /**
             * 在 semaphore.acquire() 和 semaphore.release()之间的代码，
             * 同一时刻只允许制定个数的线程进入，
             * 因为semaphore的构造方法是1，则同一时刻只允许一个线程进入，其他线程只能等待。
             * */
            semaphore.acquire();
            a = a + 1;
//      System.out.println(Thread.currentThread().getName());
//      Thread.sleep(1000);
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void doHandle(int num, int currently) throws InterruptedException {
        Thread.sleep(5000);
    }

    public static void main(String[] args) throws InterruptedException {
        final ProcessLimitor limitor = new ProcessLimitor();
        for (int index = 0; index < 2000; index++) {
            final int threadNum = index;
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    limitor.handle(threadNum);
                }
            });

            t.start();
        }

        Thread.sleep(3000);
        System.out.println("////////");
        System.out.println(limitor.a);
    }
}
